#include<iostream>
#include<string>
#include "Common.hpp"
#include "Log.hpp"
#include "NetCal.hpp"
#include "Protocol.hpp"
#include "Channel.hpp"
#include "Listener.hpp"


int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        std::cerr << "Uage:" << argv[0] << " port" << std::endl;
        exit(USAGE_ERR);
    }

    LogModule::ConsoleStrategy();
    uint16_t port = std::stoi(argv[1]);

    //构建一个业务模块
    std::shared_ptr<Cal> cal = std::make_shared<Cal>();

    //构建协议对象
    std::shared_ptr<Protocol> protocol = std::make_shared<Protocol>(
        [&cal](Request& req)->Response{
            return cal->Execute(req);
        }
    );

    //构建Listenner对象
    std::shared_ptr<Connection> conn = std::make_shared<listener>(port);
    //注册方法,该方法是Channel内部将inbuffer数据交给Protocol后返回给outbuffer
    conn->RegisterHandler([&protocol](std::string& inbuffer)->std::string {
        LOG(LogLevel::DEBUG) << "enter the register handler begin";
        std::string response_str;

        while(true)//循环处理多个完整报文
        {
            std::string package;
            if(!protocol->Decode(inbuffer,&package))
                break;
            response_str += protocol->Excute(package);
        }
        LOG(LogLevel::DEBUG) << "enter the register handler end:" << response_str; 
        return response_str;
    });
    
    //注册一个Reactor模块
    std::unique_ptr<Reactor> R = std::make_unique<Reactor>();
    R->AddConnection(conn);
    R->Start();

    return 0;
}